<?php

class Default_Model_DbTable_Confirm extends Zend_Db_Table_Abstract
{
    protected $_name    = 'spagooy_user_confirm';
	protected $_primary = 'spagooy_user_confirm_id';
	
	public function insertConfirmationKey($userId, $key, $email){	
		try {
			$data = array(
				'spagooy_user_confirm_user_id' => $userId,
				'spagooy_user_confirm_key' => $key,
				'spagooy_user_confirm_email' => $email
			);
			
			$id = $this->insert($data);
			return $id;

		} catch (Exception $e) {
			throw new Exception("Could not insertConfirmationKey(). Exception = $e");
		}
	}
	
	public function confirmNewUser($key){
		try {
			
			// kolla eposten endast en gång
			
			
			// tidsbegränsad
			
			$query = $this->select();
			$query->from(array('c' => 'spagooy_user_confirm'), array(
				'c.spagooy_user_confirm_user_id'
			));
			$query->where('c.spagooy_user_confirm_key = ?', $key);
			$user = $this->fetchAll($query);
			$a = count($user);
			if($a){
				return $user[0]->spagooy_user_confirm_user_id;
			} else {
				return false;
			}			
			
		} catch (Exception $e) {
			throw new Exception("Could not confirmNewUser(). Exception = $e");
		}
	}
	
	public function deleteConfirmationKey($userId){
		try{
			$where = $this->getAdapter()->quoteInto('spagooy_user_confirm_user_id = ?',$userId);
			$this->delete($where);			
		}catch(Exception $e){
			throw new Exception("Could not deleteConfirmationKey(\$userId). Exception = $e");			
		}
	}
	
	public function emailExists($email){
		try {
			$query = $this->select();
			$query->from(array('spagooy_user_confirm'), array(
				'spagooy_user_confirm_id'
			));
			$query->where('spagooy_user_confirm_email = ?', $email);
			$user = $this->fetchAll($query);
			return count($user);

		} catch (Exception $e) {
			Zend_Registry::get('errLog')->err('emailExists error: ' . $e);
			throw new Exception('emailExists error: ' . $e);			
		}
	}
}
